import React, { useEffect, useState } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Space,
  Card,
  Divider,
  Typography,
  message,
  InputNumber,
  Popconfirm,
} from 'antd';
import {
  SearchOutlined,
  UndoOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  ClockCircleOutlined,
  AuditOutlined
} from '@ant-design/icons';
import { getProgramRecord, programCheckProgress } from '@/services/apis/companyRegister';
import { useModel } from '@umijs/max';
import AcceptanceManagerPage from './modal';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

// 状态选项（支持状态跳转机制）
const STATUS_OPTIONS = [
  { value: 'pending', label: '待审核' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '不通过' },
  { value: 'returned', label: '已退回' },
  { value: 'in_progress', label: '进行中' },
];

// 数字化水平等级选项
const DIGITAL_LEVEL_OPTIONS = [
  { value: 'level1', label: '一级' },
  { value: 'level2', label: '二级' },
  { value: 'level3', label: '三级' },
  { value: 'level4', label: '四级' },
  { value: 'level5', label: '五级' },
];

// ---------------------- 新增：企业验收办理进度测试数据 ----------------------
// 按验收ID匹配进度记录，贴合“项目验收”业务场景（含区级、市级审核节点）
const getAcceptanceProgress = (acceptanceId: string, enterpriseName: string) => {
  const PROGRESS_DATA_MAP = {
    acc001: [
      {
        id: 'prog001',
        time: '2025/10/8 15:40',
        unit: '区经信局',
        link: '企业验收',
        result: '待审核',
        opinion: '验收材料已接收，等待区级审核',
        resultType: 'warning'
      },
      {
        id: 'prog002',
        time: '2025/10/8 10:25',
        unit: enterpriseName,
        link: '企业验收',
        result: '提交验收申请',
        opinion: '提交智能工厂数字化改造项目验收申请及全套支撑材料',
        resultType: 'info'
      },
      {
        id: 'prog003',
        time: '2025/10/7 16:30',
        unit: '第三方评估机构',
        link: '企业验收',
        result: '评估完成',
        opinion: '项目完成度100%，绩效指标达标，建议通过验收',
        resultType: 'success'
      }
    ],
    acc002: [
      {
        id: 'prog011',
        time: '2025/10/6 14:20',
        unit: '市经信局',
        link: '企业验收',
        result: '审核通过',
        opinion: '验收材料完整，评估结论合理，同意通过验收并发放奖补资金30万元',
        resultType: 'success'
      },
      {
        id: 'prog012',
        time: '2025/10/6 09:10',
        unit: '区经信局',
        link: '企业验收',
        result: '审核通过',
        opinion: '转市经信局复核',
        resultType: 'success'
      },
      {
        id: 'prog013',
        time: '2025/10/5 11:30',
        unit: enterpriseName,
        link: '企业验收',
        result: '提交验收申请',
        opinion: '提交企业数字化管理升级项目验收申请',
        resultType: 'info'
      }
    ],
    acc003: [
      {
        id: 'prog021',
        time: '2025/10/4 16:15',
        unit: '区经信局',
        link: '企业验收',
        result: '已退回',
        opinion: '缺少完整绩效数据和第三方评估报告，需补充后重新提交',
        resultType: 'warning'
      },
      {
        id: 'prog022',
        time: '2025/10/4 09:45',
        unit: enterpriseName,
        link: '企业验收',
        result: '提交验收申请',
        opinion: '提交供应链数字化改造项目验收申请',
        resultType: 'info'
      }
    ]
  };
  // 无匹配ID时返回默认进度
  return PROGRESS_DATA_MAP[acceptanceId as keyof typeof PROGRESS_DATA_MAP] || [
    {
      id: `prog-default-${acceptanceId}`,
      time: '2025/10/2 11:00',
      unit: enterpriseName,
      link: '企业验收',
      result: '提交验收申请',
      opinion: '提交项目验收申请',
      resultType: 'info'
    }
  ];
};

// 新增：办理进度列表列配置（固定5字段，统一格式）
const progressColumns = [
  {
    title: (
      <Space align="center">
        {/* <ClockCircleOutlined /> */}
        <span>时间</span>
      </Space>
    ),
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 200,
    align: 'center',
  },
  {
    title: '单位',
    dataIndex: 'departmentName',
    key: 'departmentName',
    width: 200,
    align: 'center',
  },
  {
    title: '环节',
    dataIndex: 'link',
    key: 'link',
    width: 200,
    align: 'center',
  },
  {
    title: '结果',
    dataIndex: "resultStatus",
    key: 'resultStatus',
    width: 200,
    align: 'center',
  },
  {
    title: '意见',
    dataIndex: 'auditRemark',
    key: 'auditRemark',
    width: 200,
    render: (opinion: string) => (
      <Text>
        {opinion}
      </Text>
    ),
  },
];

// 获取数字化水平等级显示文本
const getDigitalLevelText = (level: string) => {
  const levelMap: Record<string, string> = {
    level1: '一级',
    level2: '二级',
    level3: '三级',
    level4: '四级',
    level5: '五级',
  };
  return levelMap[level] || level;
};

const PilotEnterpriseAcceptanceManagement: React.FC = () => {
  // 状态管理：新增进度相关状态
  const [acceptanceList, setAcceptanceList] = useState([]);
  const [searchForm] = Form.useForm(); // 搜索表单
  const [currentAcceptance, setCurrentAcceptance] = useState<any>(null); // 当前操作的验收记录
  const { initialState, setInitialState } = useModel('@@initialState');
  const [pageProps, setPageProps] = useState<{ current: number, pageSize: number, total: number }>({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const {
    modalProps,
    setModalProps,
  } = useModel("AcceptanceManager.modal")
  const [modalVisible, setModalVisible] = useState({
    edit: false, // 编辑弹窗
    review: false, // 审核弹窗
    progress: false, // 新增：进度弹窗控制
  });
  const [currentProgressList, setCurrentProgressList] = useState<any[]>([]); // 新增：当前验收的进度数据

  // ---------------------- 新增：打开进度弹窗逻辑 ----------------------
  const handleProgressOpen = (record: any) => {
    programCheckProgress({companyId:record.companyId}).then(res => {
          const {code, data} = res
          if(code == "0"){
            setCurrentAcceptance(record);
            setCurrentProgressList(data);
          }
        })
        setModalVisible({
          ...modalVisible,
          progress: true
        });
  };

  // 1. 搜索功能：根据企业名称和状态筛选
  const handleSearch = async () => {
    const searchValues = await searchForm.validateFields();
    searchUsers({ ...searchValues, current: pageProps.current, size: pageProps.pageSize })
  };
  const usersPageOnchange = (current: any, pageSize: any) => {
    searchUsers({ ...searchForm.getFieldsValue(), current, size: pageSize })
  }
  // 2. 重置搜索：恢复初始列表
  const handleReset = () => {
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
    searchForm.resetFields();
  };

  const handleDelete = (recordId: string) => {
    message.info("业务逻辑待确认")
    // removeRecord({ id: recordId }).then(res => {
    //   const { code } = res
    //   if (code == "0") {
    //     //message.success("企业备案记录删除成功")
    //     searchUsers({ ...searchForm.getFieldsValue(), current: pageProps.current, size: pageProps.pageSize })
    //   }
    // })
  };

  // 4. 打开编辑弹窗：新增关闭进度弹窗逻辑
  const handleEditOpen = (record: any, title: string) => {
 
    setModalProps(prev => ({ ...prev, visible: true, record, title }))
  };
  useEffect(() => {
    searchUsers({ current: pageProps.current, size: pageProps.pageSize })
  }, [])
  const searchUsers = (values: any) => {
    getProgramRecord({
      ...values,
      loginInArea: initialState?.currentUser.data.loginInArea,
      userType: initialState?.currentUser.data.userType,
    }).then(res => {
      const { code, data } = res
      if (code == "0") {
        setAcceptanceList(data.records)
        setPageProps({
          current: data.current,
          pageSize: data.size,
          total: data.total
        })
        //message.success("请求成功")
      }
    })
  }
  // 表格列配置：新增“进度”按钮（加宽操作列）
  const tableColumns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: "10%",
      align: 'center',
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      width: "15%",
    },
    {
      title: '数字化水平等级',
      dataIndex: 'digitalLevel',
      key: 'digitalLevel',
      width: "10%",
      align: 'center',
      render: (level: string) => getDigitalLevelText(level),
    },
    // {
    //   title: (
    //     <div style={{ whiteSpace: 'normal', lineHeight: '1.2' }}>
    //       拟对企业奖补
    //       <br />
    //       资金总额（万元）
    //     </div>
    //   ),
    //   dataIndex: 'subsidyAmount',
    //   key: 'subsidyAmount',
    //   width: "10%",
    //   align: 'right',
    // },

    {
      title: '环节',
      dataIndex: 'link',
      key: 'link',
      width: "10%",
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'resultStatus',
      key: 'resultStatus',
      width: "10%",
      align: 'center',
    },
    {
      title: '操作',
      key: 'operation',
      width: "30%",// 加宽操作列容纳4个按钮
      align: 'center',
      render: (_: any, record: any) => (
        <Space size={2}>
          <Popconfirm
            title="是否删除"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button
              size="small"
              type="primary"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>

          <Button 
          disabled={(() => {
              if(initialState?.currentUser.data.userType == "county"){
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if(initialState?.currentUser.data.userType == "city"){
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
          size="small" type="primary" icon={<EditOutlined />} onClick={() => handleEditOpen(record, "编辑项目验收管理")}>
            编辑
          </Button>
          <Button
            type="primary"
            size="small"
            // disabled={record.auditStatus != 'pending'}
            disabled={(() => {
              if(initialState?.currentUser.data.userType == "county"){
                return record.resultStatus != "待县（市、区）经商局审核"
              }
              if(initialState?.currentUser.data.userType == "city"){
                return record.resultStatus != "待市经信局审核"
              }
              return false
            })()}
            icon={<AuditOutlined />}
            onClick={() => handleEditOpen(record, "审核项目验收管理")}
          >
             {
              (() => {
              if(initialState?.currentUser.data.userType == "county" && record.resultStatus == "待县（市、区）经商局审核"){
                return "审核"
              }
              if(initialState?.currentUser.data.userType == "city" && record.resultStatus == "待市经信局审核"){
                return "审核"
              }
              return "已审核"
            })()
            }
          </Button>
          <Button
            size="small"
            type="primary"
            icon={<ClockCircleOutlined />}
            onClick={() => handleProgressOpen(record)}
          >
            进度
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      {/* 页面标题 */}
      <div
        style={{
          fontSize: 16,
          fontWeight: 500,
          color: '#1f2937',
          marginBottom: 12,
        }}
      >
        项目验收管理
      </div>

      {/* 第一部分：搜索栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          initialValues={{ status: '' }} // 初始不筛选状态
        >
          <Form.Item
            name="enterpriseName"
            label="企业名称"
            rules={[{ whitespace: true, message: '请输入有效企业名称' }]}
          >
            <Input placeholder="请输入企业名称" style={{ width: '220px' }} />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: '180px' }} allowClear>
              {STATUS_OPTIONS.map((option) => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset} icon={<UndoOutlined />}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card
        style={{
          borderRadius: 12,
          boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
          // height: 'calc(100vh - 120px)', // 精确高度，保证内部滚动
          // overflowY: 'auto', // 内部滚动
          padding: '24px',
        }}
      >
        {/* 第二部分：企业验收列表 */}
        <Table
          columns={tableColumns as any}
          dataSource={acceptanceList}
          rowKey="id"
          pagination={{
            pageSize: pageProps.pageSize,
            current: pageProps.current, total: pageProps.total, showSizeChanger: true,
            onChange: usersPageOnchange
          }}
          bordered
          className='custom-table1'
          scroll={{ y: 'calc(100vh - 450px)' }}
          locale={{ emptyText: '暂无项目验收管理信息' }}
        />
      </Card>
      <AcceptanceManagerPage searchCallFun={handleSearch} />
      {/* ---------------------- 新增：企业验收办理进度弹窗 ---------------------- */}
      <Modal
        title={`${currentAcceptance?.enterpriseName || '企业'}项目验收办理进度`}
        open={modalVisible.progress}
        onCancel={() => setModalVisible({ ...modalVisible, progress: false })}
        maskClosable={false}
        width={900}
        footer={[
          <Button key="close" onClick={() => setModalVisible({ ...modalVisible, progress: false })}>
            关闭
          </Button>
        ]}
        bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }}
      >
        <Card bordered={false}>
          <Table
            columns={progressColumns as any}
            dataSource={currentProgressList}
            rowKey="id"
            className="custom-table"

            pagination={false} // 进度列表完整展示，不分页
            bordered
            locale={{ emptyText: '暂无该项目的验收办理进度记录' }}
            rowClassName={() => 'hover:bg-gray-50'} // 行悬浮高亮，提升交互体验
          />
        </Card>
      </Modal>
    </div>
  );
};

export default PilotEnterpriseAcceptanceManagement;